package pay

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"gitee.com/bobo-rs/innovideo-services/library/services/pay"
	"github.com/gogf/gf/v2/frame/g"
)

// 支付回调更新数据
func (p *sPay) Notify(ctx context.Context, in model.PayNotifyInput) (err error) {
	// 异步回调处理逻辑
	var handlePayNotify = func(ctx context.Context, payNo, tradeNo, event string, arg ...interface{}) error {
		// 按事件更新结果
		switch in.Event {
		case enums.PayEventCoins:
			return service.PgCoin().NotifyPGCoin(ctx, model.PGCoinPayNotifyInput{
				PayNo:   payNo,
				PayType: in.PayType,
				TradeNo: tradeNo,
			})
		default:
			return exception.Newf(`回调更新支付事件[%s]不存在`, string(in.Event))
		}
	}

	// 记录回调结果
	defer func() {
		if err != nil {
			g.Log().Debug(ctx, `支付回调处理失败`, in, err)
		} else {
			g.Log().Info(ctx, `支付回调处理成功`, in)
		}
	}()

	// 支付回调
	_, err = pay.New().Register(ctx, string(in.PayType)).Notify(ctx, handlePayNotify)
	return err
}
